<template>
    <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons'>
        
        <template #enable='{record}'>
            <a-tag v-if='record.enable' color='#87d068'>{{$t('enable')}}</a-tag>
            <a-tag v-else>{{$t('disable')}}</a-tag>
        </template>


        <template #$action="{record}">
            <template v-if="resourceStore.hasPermission('system:member:update') && !record.canSuper">
                <BTextButton type='primary' @click='update(record)'>{{$t('edit')}}</BTextButton>
            </template>
            <template v-if="resourceStore.hasPermission('system:member:delete') && !record.canSuper">
                <BTextButton type='error' @click='del(record)'>{{$t('delete')}}</BTextButton>
            </template>
            <BTextButton @click='openResetpwd(record)'>修改密码</BTextButton>
        </template>
    </BPTable>

    <BDrawer v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit'>
        <Edit :row="currentRow" ref="formRef" />
    </BDrawer>


    <BDrawer v-model:visible='visibleResetPwd' title='修改密码' width='600px' :confirm='submitResetpwd'>
        <a-form ref='resetpwdFormRef' :label-col='{span : 5}' :model='resetpwdFormData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='resetpwdFormData.id' />
            </a-form-item>
            <a-form-item label='新密码' name='password' :rules="[{required : true, validator : pwdValidator}]">
                <a-input-password v-model:value='resetpwdFormData.password' :maxlength="30"  show-count />
            </a-form-item>
        </a-form>
    </BDrawer>
</template>

<script lang='ts' setup>
    import { ref } from "vue";
    import { deleteApi, pageApi, restpwdApi } from '@/api/system/Member'
    import { parseTime, recursionFn } from "@/utils";
    import { useResourceStore } from "@/store/resource";
    import Edit from './Edit.vue';
    import { Modal, message } from "ant-design-vue";
    import { useI18nStore } from "@/store/i18n";
    import QrCode from '@/components/QrCode.vue'
import { Rule } from "ant-design-vue/es/form";

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const currentRow = ref<any>()

    const tableRef = ref()


    const visibleResetPwd = ref(false)
    const resetpwdFormRef = ref()
    const resetpwdFormData = ref({
        id : 0,
        password : ''
    })
    const pwdValidator = async (_rule: Rule, value: string) => {
        if(value.length < 6) {
            return Promise.reject("密码长度至少6位");
        }
        return Promise.resolve()
    }

    function openResetpwd(row) {
        resetpwdFormData.value.id = row.id
        resetpwdFormData.value.password = ''
        visibleResetPwd.value = true
    }

    async function submitResetpwd() {
        const params = await resetpwdFormRef.value.validate()
        const res = await restpwdApi(params.id, params.password)
        if(res.success) {
            visibleResetPwd.value = false
            message.success('修改成功')
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission("user:teacher:add")) {
        buttons.value.push({
            button : 'add',
            func : () => {
                currentRow.value = null
                dialogTitle.value = '新增'
                visible.value = true
            }
        })
    }


    const columns = ref<Column[]>([
        {
            dataIndex : 'account',
            title : '账号',
            inSearch : true,
        },

        {
            dataIndex : 'name',
            title : '姓名',
            inSearch : true,
        },

        {
            title : i18n.t('enable'),
            dataIndex : 'enable',
            align : 'center',
        },
        

        {
            title : i18n.t('role'),
            dataIndex : 'role',
            align : 'center',
            customRender({ record }) {
                if(record.canSuper) return '超级管理'
                return record.roleNames ? record.roleNames.join(' ') : ''
            }
        },

        {
            dataIndex : 'tel',
            title : '手机号码',
        },

        // {
        //     title : '最近登录',
        //     dataIndex : 'lastLoginTime',
        //     align : 'center',
        //     customRender({text}) {
        //         return parseTime(text)
        //     }
        // },

        {
            title : i18n.t('operation'),
            dataIndex : '$action',
            align : 'center',
            // $edit : resourceStore.hasPermission('user:member:update') ? (row) => {
            //     dialogTitle.value = i18n.t('edit')
            //     currentRow.value = row
            //     visible.value = true
            // } : undefined,

            // $delete : resourceStore.hasPermission('system:member:delete') ? async (row) => {
            //     const res = await deleteApi(row.id)
            //     if(res.success) {
            //         message.success(i18n.t('deleteSuccess'))
            //         tableRef.value.load()
            //     }else {
            //         message.error(res.msg)
            //     }
            // } : undefined
        }
    ])

    const dataRows = ref<any[]>([])

    function update(row) {
            dialogTitle.value = i18n.t('edit')
            currentRow.value = row
            visible.value = true
    }

    async function del(row) {
        Modal.confirm({
            title : i18n.t('confirmDel', [row.name]),
            async onOk() {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }
        })
            
    }

    async function submit() {
        const res = await formRef.value.submit()
        if(res.success) {
            tableRef.value.reload()
            visible.value = false
            message.success('保存成功')
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }
    
</script>